package com.che.software.testato.domain.dao.jdbc.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.che.software.testato.domain.dao.IProjectDAO;
import com.che.software.testato.domain.dao.jdbc.adao.AbstractDAO;
import com.che.software.testato.domain.dao.jdbc.exception.ProjectCreationDAOException;
import com.che.software.testato.domain.dao.jdbc.exception.ProjectSearchDAOException;
import com.che.software.testato.domain.entity.Project;
import com.che.software.testato.domain.entity.search.ProjectSearch;

/**
 * JDBC implementation of the DAO interface dedicated to the projects
 * management.
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @copyright Che Software.
 * @license GNU General Public License.
 * @see AbstractDAO, IProjectDAO.
 * @since July, 2011.
 * 
 *        This file is part of Testato.
 * 
 *        Testato is free software: you can redistribute it and/or modify it
 *        under the terms of the GNU General Public License as published by the
 *        Free Software Foundation, either version 3 of the License, or (at your
 *        option) any later version.
 * 
 *        Testato is distributed in the hope that it will be useful, but WITHOUT
 *        ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *        FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 *        for more details.
 * 
 *        You should have received a copy of the GNU General Public License
 *        along with Testato. If not, see <http://www.gnu.org/licenses/>.
 * 
 *        Testato's logo is a creation of Arrioch
 *        (http://arrioch.deviantart.com/) and it's distributed under the terms
 *        of the Creative Commons License.
 */
@Repository("projectDAO")
public class ProjectDAO extends AbstractDAO implements IProjectDAO {

	/**
	 * Constants.
	 */
	private static final Logger LOGGER = Logger.getLogger(ProjectDAO.class);

	/**
	 * Creates a project from his name.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param name the name of the project to create.
	 * @since July, 2011.
	 * @throws ProjectCreationDAOException if an error occurs during the
	 *         creation.
	 */
	@Override
	public void createProjectFromName(String name) throws ProjectCreationDAOException {
		LOGGER.debug("createProjectFromName(" + name + ").");
		Connection connection = null;
		try {
			connection = getDataSource().getConnection();
			getQueryRunner().update(connection, "INSERT INTO project(project_id, \"name\") VALUES(nextval('project_seq'), ?) ", new Object[] { name });
		} catch (SQLException e) {
			throw new ProjectCreationDAOException(e);
		} finally {
			if (null != connection) {
				DbUtils.closeQuietly(connection);
			}
		}
	}

	/**
	 * Checks if a project with given name is already existing.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param name the project name to check
	 * @return true if this name is already used, else false.
	 * @since July, 2011.
	 * @throws ProjectSearchDAOException if an error occurs during the search.
	 */
	@Override
	public boolean isProjectExists(String name) throws ProjectSearchDAOException {
		LOGGER.debug("isProjectExists().");
		Connection connection = null;
		try {
			connection = getDataSource().getConnection();
			return (Boolean) getQueryRunner().query(connection, "SELECT EXISTS( SELECT project_id FROM project WHERE name = ?) AS result ", new ScalarHandler("result"), new Object[] { name });
		} catch (SQLException e) {
			throw new ProjectSearchDAOException(e);
		} finally {
			if (null != connection) {
				DbUtils.closeQuietly(connection);
			}
		}
	}

	/**
	 * Project search from a bean of criterions.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param searchBean the criterions to use for the search.
	 * @return the resulting object list.
	 * @since July, 2011.
	 * @throws ProjectSearchDAOException if an error occurs during the search.
	 */
	@Override
	public List<Project> searchProject(ProjectSearch searchBean) throws ProjectSearchDAOException {
		LOGGER.debug("searchProject().");
		Connection connection = null;
		try {
			connection = getDataSource().getConnection();
			List<Object> params = new ArrayList<Object>();
			return getQueryRunner().query(connection, getProjectSearchQueryFromCriterion(searchBean, params), new BeanListHandler<Project>(Project.class), params.toArray());
		} catch (SQLException e) {
			throw new ProjectSearchDAOException(e);
		} finally {
			if (null != connection) {
				DbUtils.closeQuietly(connection);
			}
		}
	}

	/**
	 * Recovery of the project search query from criterion.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param searchBean the object containing the criterions.
	 * @param params the parameters list corresponding to the built query.
	 * @return the built query.
	 * @since July, 2011.
	 */
	private String getProjectSearchQueryFromCriterion(ProjectSearch searchBean, List<Object> params) {
		LOGGER.debug("getProjectSearchQueryFromCriterion().");
		setWhereClauseEnabled(false);
		StringBuilder sBuilder = new StringBuilder("SELECT project_id AS projectId, \"name\" FROM project ");
		if (null != searchBean && 0 != searchBean.getProjectId()) {
			sBuilder.append(getWhereClauseBegin());
			sBuilder.append("project_id = ?");
			params.add(searchBean.getProjectId());
		}
		return sBuilder.toString();
	}
}